import { ref, computed, watch } from 'vue'
import type { ConversionStatus, ValidationError, ConversionError } from '@/types'
import { validateJson } from '@/utils/validator'
import { jsonToToml } from '@/utils/converter'

// 指数退避防抖函数，根据输入频率和长度动态调整延迟
function createSmartDebounce() {
  let timeoutId: number
  let lastCallTime = 0
  let consecutiveCalls = 0
  let baseDelay = 300

  return function <T extends (...args: any[]) => void>(func: T): T {
    return ((...args: any[]) => {
      clearTimeout(timeoutId)
      const now = Date.now()
      const timeSinceLastCall = now - lastCallTime

      // 计算连续调用频率
      if (timeSinceLastCall < 200) {
        consecutiveCalls++
      } else {
        consecutiveCalls = 1
      }
      lastCallTime = now

      // 动态调整延迟
      let delay = baseDelay
      if (args.length > 0 && typeof args[0] === 'string') {
        const inputLength = args[0].length

        // 基础延迟：根据输入长度
        if (inputLength > 10000) {
          delay = 800
        } else if (inputLength > 5000) {
          delay = 600
        } else if (inputLength > 1000) {
          delay = 400
        }

        // 指数退避：根据连续调用频率
        const exponentialDelay = Math.min(200 * Math.pow(1.5, consecutiveCalls - 1), 1000)
        delay = Math.max(delay, exponentialDelay)
      }

      timeoutId = setTimeout(() => {
        consecutiveCalls = 0
        func(...args)
      }, delay)
    }) as T
  }
}

// 快速JSON预检查，避免对明显不完整的输入进行完整验证
function quickJsonCheck(json: string): { canProceed: boolean; reason?: string } {
  const trimmed = json.trim()

  // 空字符串
  if (!trimmed) {
    return { canProceed: false, reason: 'empty' }
  }

  // 检查基本括号匹配
  let braceCount = 0
  let bracketCount = 0
  let inString = false
  let escapeNext = false

  for (let i = 0; i < trimmed.length; i++) {
    const char = trimmed[i]

    if (escapeNext) {
      escapeNext = false
      continue
    }

    if (char === '\\') {
      escapeNext = true
      continue
    }

    if (char === '"') {
      inString = !inString
      continue
    }

    if (inString) continue

    if (char === '{') braceCount++
    else if (char === '}') braceCount--
    else if (char === '[') bracketCount++
    else if (char === ']') bracketCount--
  }

  // 如果括号不匹配，JSON肯定不完整
  if (braceCount !== 0 || bracketCount !== 0) {
    return { canProceed: false, reason: 'unmatched_brackets' }
  }

  // 如果以未闭合的字符串结尾，可能不完整
  if (inString) {
    return { canProceed: false, reason: 'unclosed_string' }
  }

  // 如果以逗号结尾，可能不完整
  if (trimmed.endsWith(',')) {
    return { canProceed: false, reason: 'trailing_comma' }
  }

  // 如果输入过大，给出警告
  if (trimmed.length > 50000) {
    return { canProceed: false, reason: 'too_large' }
  }

  return { canProceed: true }
}

export function useConverter() {
  // 状态
  const jsonInput = ref('')
  const tomlOutput = ref('')
  const conversionStatus = ref<ConversionStatus>('idle')
  const validationError = ref<ValidationError | null>(null)
  const conversionError = ref<ConversionError | null>(null)
  const addWindowsEnv = ref(false)
  const isAutoConvert = ref(true)

  // 性能监控状态
  const isInputTooLarge = ref(false)
  const inputSizeWarning = ref('')

  // 创建智能防抖函数
  const smartDebounce = createSmartDebounce()

  // 计算属性
  const isValidJson = computed(() => {
    if (!jsonInput.value.trim()) return true
    const result = validateJson(jsonInput.value)
    validationError.value = result.error || null
    return result.isValid
  })

  const canConvert = computed(() => {
    return isValidJson.value && jsonInput.value.trim() !== '' && !isInputTooLarge.value
  })

  const hasError = computed(() => {
    return validationError.value !== null || conversionError.value !== null
  })

  const currentError = computed(() => {
    return conversionError.value || validationError.value
  })

  // 验证JSON（智能防抖 + 快速预检查）
  const validateInput = smartDebounce(() => {
    if (!jsonInput.value.trim()) {
      conversionStatus.value = 'idle'
      validationError.value = null
      conversionError.value = null
      tomlOutput.value = ''
      isInputTooLarge.value = false
      inputSizeWarning.value = ''
      return
    }

    // 快速预检查
    const quickCheck = quickJsonCheck(jsonInput.value)
    if (!quickCheck.canProceed) {
      switch (quickCheck.reason) {
        case 'empty':
          conversionStatus.value = 'idle'
          return
        case 'unmatched_brackets':
        case 'unclosed_string':
        case 'trailing_comma':
          // JSON不完整，暂时不验证
          conversionStatus.value = 'idle'
          return
        case 'too_large':
          isInputTooLarge.value = true
          inputSizeWarning.value = '输入内容过大，可能影响性能'
          conversionStatus.value = 'error'
          conversionError.value = {
            type: 'validation',
            message: '输入内容过大（超过50KB），请减少输入内容或分批处理',
          }
          return
        default:
          conversionStatus.value = 'idle'
          return
      }
    }

    // 重置大文件警告
    isInputTooLarge.value = false
    inputSizeWarning.value = ''

    conversionStatus.value = 'validating'

    const result = validateJson(jsonInput.value)
    validationError.value = result.error || null

    if (result.isValid && isAutoConvert.value) {
      convertJson()
    } else {
      conversionStatus.value = result.isValid ? 'idle' : 'error'
    }
  })

  // 转换JSON到TOML
  function convertJson() {
    if (!canConvert.value) {
      return
    }

    conversionStatus.value = 'converting'
    conversionError.value = null

    const result = jsonToToml(jsonInput.value, addWindowsEnv.value)

    if (result.success && result.toml) {
      tomlOutput.value = result.toml
      conversionStatus.value = 'success'
    } else {
      conversionError.value = result.error || null
      conversionStatus.value = 'error'
      tomlOutput.value = ''
    }
  }

  // 手动转换
  function manualConvert() {
    if (canConvert.value) {
      convertJson()
    }
  }

  // 清空所有内容
  function clearAll() {
    jsonInput.value = ''
    tomlOutput.value = ''
    conversionStatus.value = 'idle'
    validationError.value = null
    conversionError.value = null
  }

  // 设置JSON输入
  function setJsonInput(value: string) {
    jsonInput.value = value
  }

  // 获取TOML输出
  function getTomlOutput(): string {
    return tomlOutput.value
  }

  // 复制TOML到剪贴板
  async function copyTomlToClipboard(): Promise<boolean> {
    try {
      if (!tomlOutput.value) {
        return false
      }

      await navigator.clipboard.writeText(tomlOutput.value)
      return true
    } catch (error) {
      console.error('复制失败:', error)
      return false
    }
  }

  // 监听JSON输入变化
  watch(jsonInput, () => {
    validateInput()
  })

  // 监听Windows环境变量选项变化
  watch(addWindowsEnv, () => {
    if (canConvert.value && isAutoConvert.value) {
      convertJson()
    }
  })

  // 监听自动转换选项变化
  watch(isAutoConvert, (newValue) => {
    if (newValue && canConvert.value) {
      convertJson()
    }
  })

  return {
    // 状态
    jsonInput,
    tomlOutput,
    conversionStatus,
    validationError,
    conversionError,
    addWindowsEnv,
    isAutoConvert,
    isInputTooLarge,
    inputSizeWarning,

    // 计算属性
    isValidJson,
    canConvert,
    hasError,
    currentError,

    // 方法
    convertJson,
    manualConvert,
    clearAll,
    setJsonInput,
    getTomlOutput,
    copyTomlToClipboard,
  }
}
